package com.xianggu.mybatis.configFile;

import com.xianggu.mybatis.enums.MysqlConnectParam;
import com.xianggu.mybatis.utils.ObjectTranUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.net.URL;
import java.util.Map;

public class YamlParser implements FileReaderStrategy{
    public static void main(String[] args) {

        // 假设application.yml文件在项目根目录下，如果在其他位置需要修改路径
        InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream("application.yml");
        Yaml yaml = new Yaml();
        Map<String, Object> data = yaml.load(inputStream);

        Map<String, Object> springData = (Map<String, Object>) data.get("spring");
        Map<String, Object> datasource = (Map<String, Object>) springData.get("datasource");

        MysqlConnectParam object = ObjectTranUtils.MapToObject(MysqlConnectParam.class, datasource);

        String url = (String) datasource.get("url");
        String username = (String) datasource.get("username");
        String password = (String) datasource.get("password");
        String driverClassName = (String) datasource.get("driver-class-name");

        System.out.println("URL: " + url);
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
        System.out.println("Driver Class Name: " + driverClassName);

    }

    @Override
    public MysqlConnectParam readFile() throws IOException {
        URL resource = super.getClass().getClassLoader().getResource("application.yml");

        // 找不到文件则跳过该策略
        if(resource == null) {
            return null;
        }

        File file = new File(resource.getFile());
        if (file.exists()) {
            // 这里可以添加实际的读取文件内容的代码，简单返回一个标识
            Yaml yaml = new Yaml();
            Map<String, Object> data = yaml.load(new FileInputStream(file));

            Map<String, Object> springData = (Map<String, Object>) data.get("spring");
            Map<String, Object> datasource = (Map<String, Object>) springData.get("datasource");

            MysqlConnectParam connectParam = ObjectTranUtils.MapToObject(MysqlConnectParam.class, datasource);

            connectParam.setDriverClassName(datasource.get("driver-class-name").toString());
            connectParam.setInitialSize( datasource.get("initial-size") == null ? 0 : Integer.parseInt(datasource.get("initial-size").toString()));
            connectParam.setMinIdle( datasource.get("min-idle") == null ? 0 : Integer.parseInt(datasource.get("min-idle").toString()));
            return connectParam;
        }
        return null;
    }
}